package com.slipper.system.affix.service;

import java.io.File;
import java.util.List;

import com.slipper.util.Tool;
import com.slipper.system.affix.dao.AffixItemDao;
import com.slipper.system.affix.bo.AffixItemBO;
import com.slipper.util.UUID;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.slipper.core.transaction.ReadTransactional;
import com.slipper.core.transaction.WriteTransactional;

@Service
@ReadTransactional
public class AffixItemService {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private AffixItemDao affixItemDao;

    public AffixItemBO queryBy(String id) {
        return affixItemDao.queryBy(id);
    }

    @WriteTransactional
    public AffixItemBO save(AffixItemBO bo) {
        if (Tool.isNotBlank(bo.getAffixId())) {
            bo.setOrdinal(affixItemDao.queryMaxOrdinal(bo.getAffixId()) + 1);
        }
        if (Tool.isNotBlank(bo.getId())) {
            this.affixItemDao.update(bo);
        } else {
            bo.setId(UUID.getUUID());
            bo.setCreateTime(System.currentTimeMillis());
            this.affixItemDao.insert(bo);
        }
        return bo;
    }

    @WriteTransactional
    public Integer delete(String id) {
        if (Tool.isBlank(id)) return 0;

        AffixItemBO bo = affixItemDao.queryBy(id);
        if (bo != null && Tool.isNotBlank(bo.getSavePath())) {
            File file = new File(bo.getSavePath());
            if (file.isFile() && file.exists()) {
                if (!file.delete()) {
                    logger.warn("文件删除失败：{}", bo.getSavePath());
                }
            }
        }
        return affixItemDao.delete(id);
    }

    @WriteTransactional
    public Integer deleteAll(String[] ids) {
        int result = 0;
        for (String id : ids) {
            result += delete(id);
        }
        return result;
    }

    public List<AffixItemBO> queryList(AffixItemBO bo) {
        return this.affixItemDao.queryList(bo);
    }

    public AffixItemBO queryByAffixId(String affixId) {
        List<AffixItemBO> itemList = affixItemDao.queryByAffixId(affixId);
        return itemList.isEmpty() ? null : itemList.getFirst();
    }

    @WriteTransactional
    public void saveList(List<AffixItemBO> affixItemList) {
        if (affixItemList == null) return;

        affixItemList.forEach(template -> {
            if (affixItemDao.queryBy(template.getId()) != null) {
                affixItemDao.update(template);
            } else {
                affixItemDao.insert(template);
            }
        });
    }
}
